import { UploadOutlined } from '@ant-design/icons';
import { Button, Modal, Upload } from 'antd';
import type { UploadFile, UploadProps } from 'antd/es/upload/interface';
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import type { UploadDialogProps } from './data';
//useImperativeHandle
const ChildUpload: React.FC<UploadDialogProps> = (props, uploadRef) => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [visible, setVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const props1: UploadProps = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
  };
  useEffect(() => {
    setVisible(props.visible);
  }, [props.visible]);
  useImperativeHandle(uploadRef, () => {
    // return返回的值就可以被父组件获取到,没返回的值就获取不到
    return {
      fileList: fileList,
    };
  });
  return (
    <div>
      <Modal
        title={props.title}
        okButtonProps={{ loading: loading }}
        visible={visible}
        onOk={async () => {
          setLoading(true);
          await props.onOk();
          setLoading(false);
        }}
        onCancel={() => {
          props.onCancel();
        }}
      >
        <Upload {...props1}>
          <Button icon={<UploadOutlined />}>Select File</Button>
        </Upload>
      </Modal>
    </div>
  );
};
const ToeUpload = forwardRef<unknown, UploadDialogProps>(ChildUpload);

export default ToeUpload;
